// JS控制并发请求数量

var limitRequest = (max) => {
    let queue = []
    let curSum = 0

    const run = async (fn) => {
        try{
            curSum++;
            const nowFn = queue.shift()
            await nowFn()
        }catch(err){

        }finally{
            curSum--;
            if(queue.length > 0){
                run()
            }
        }
    }

    return async (fn) => {
        queue.push(fn)
        if(curSum < max){
            run()
        }

    }
}


let a = () => new Promise((resolve) => {
    setTimeout(() => { resolve(1) }, 1000)
}).then((data) => console.log(data))

let b = () => new Promise((resolve) => {
    setTimeout(() => { resolve(2) }, 1000)
}).then((data) => console.log(data))


let c = () => new Promise((resolve) => {
    setTimeout(() => { resolve(3) }, 1000)
}).then((data) => console.log(data))


let d = () => new Promise((resolve) => {
    setTimeout(() => { resolve(4) }, 1000)
}).then((data) => console.log(data))

const request = limitRequest(2)
request(a)
request(b)
request(c)
request(d)


